import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * @author wcj
 * @Date 2021/6/17 15:47
 * @Version 1.0
 */
public class CyclicBarrierTest {

    public static void main(String[] args) {
//        test1();
        test2();
    }

    /**
     * CyclicBarrier：可循环使用的屏障，构造器中的整型代表阻塞的线程数量，当线程数量阻塞到一定量，再进行之后的操作
     * 需要注意，CyclicBarrier的计数器是可以进行重置的
     */
    public static void test1() {

        CyclicBarrier cyclicBarrier = new CyclicBarrier(2);

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    cyclicBarrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
                System.out.println(1);
            }
        }).start();

        try {
            cyclicBarrier.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (BrokenBarrierException e) {
            e.printStackTrace();
        }
        System.out.println(2);
    }

    public static void test2() {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(2, new A());

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    cyclicBarrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
                System.out.println(1);
            }
        }).start();

        try {
            cyclicBarrier.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (BrokenBarrierException e) {
            e.printStackTrace();
        }
        System.out.println(2);
    }
}

class A implements Runnable {

    @Override
    public void run() {
        System.out.println(3);
    }
}
